package com.hdyg.sixg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.allen.library.SuperTextView;
import com.hdyg.sixg.R;
import com.hdyg.sixg.activity.MainActivity;
import com.hdyg.sixg.activity.WebActivity;
import com.hdyg.sixg.activity.common.AppManager;
import com.hdyg.sixg.activity.home.CurrentMoneyActivity;
import com.hdyg.sixg.activity.home.ScanActivity;
import com.hdyg.sixg.adapter.FMMainBiAdapter;
import com.hdyg.sixg.adapter.FMMainMenuAdapter;
import com.hdyg.sixg.entry.FragMainBean;
import com.hdyg.sixg.entry.NativeGuideBean;
import com.hdyg.sixg.mvp.Contrant.CFragMain;
import com.hdyg.sixg.mvp.base.BaseUrl;
import com.hdyg.sixg.mvp.base.GetParamUtil;
import com.hdyg.sixg.mvp.base.SpMsg;
import com.hdyg.sixg.mvp.presenter.PFragMain;
import com.hdyg.sixg.util.DataCenter;
import com.hdyg.sixg.util.LangUtil.MultiLanguageType;
import com.hdyg.sixg.util.LangUtil.MultiLanguageUtil;
import com.hdyg.sixg.util.PopWindowUtil;
import com.hdyg.sixg.util.SPUtils;
import com.hdyg.sixg.util.StringUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import java.util.List;
import butterknife.BindView;

/**
 * @author CZB
 * @describe 首页
 * @time 2019/4/3 15:47
 */
public class MainFragment extends BaseFragment implements CFragMain.IVFragMain {

    private static final int SCAN_REQUEST_CODE = 0x000001;
    private final static int REQUEST_CODE = 0x00002;

    @BindView(R.id.ll_top_left)
    LinearLayout llTopLeft;
    @BindView(R.id.iv_top_left)
    ImageView ivTopLeft;
    @BindView(R.id.iv_top_right)
    ImageView ivTopRight;
    @BindView(R.id.tv_top_left)
    TextView tvTopLeft;
    @BindView(R.id.ll_top_right)
    LinearLayout llTopRight;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_user_level)
    TextView tvUserLevel;
    @BindView(R.id.sv_notice)
    SuperTextView svNotice;
    @BindView(R.id.sv_all_money)
    SuperTextView svAllMoney;
    @BindView(R.id.sv_current_money)
    SuperTextView svCurrentMoney;
    @BindView(R.id.rv_menu)
    RecyclerView rvMenu;
    @BindView(R.id.rv_bi)
    RecyclerView rvBi;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;

    private List<NativeGuideBean> menuDatas;
    private FMMainMenuAdapter mAdapter;
    private FMMainBiAdapter biAdapter;
    private CFragMain.IPFragMain mPresenter;
    private List<FragMainBean.CoinsBean> coins;
    private FragMainBean dataBean;
    private boolean isFirsetIncome = true; //  第一次进入
    private String langType;
    private boolean need = false;
    private PopupWindow mPopupWindow;


    @Override
    protected void createPresenter() {
        mPresenter = new PFragMain(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initView() {
        onRefresh();
        langType = SPUtils.get(SpMsg.LANG, MultiLanguageType.ZH.typeKey);
        if (langType.equals(MultiLanguageType.ZH.typeKey)) {
            tvTopLeft.setText(Html.fromHtml("<u>" + getResources().getString(R.string.lang_zh) + "</u>"));
            ivTopLeft.setImageResource(R.mipmap.lang_china);
        } else {
            tvTopLeft.setText(Html.fromHtml("<u>" + getResources().getString(R.string.lang_en) + "</u>"));
            ivTopLeft.setImageResource(R.mipmap.lang_english);
        }

        ivTopRight.setImageResource(R.mipmap.main_scan);
        ivTopRight.setVisibility(View.VISIBLE);
        rvMenu.setLayoutManager(new GridLayoutManager(mContext, 3));
        rvBi.setLayoutManager(new LinearLayoutManager(mContext));
        menuDatas = DataCenter.getFragmenMainMenuData();
        initAdapter();
    }

    private void onRefresh() {
        srlRefresh.setOnRefreshListener(refreshLayout -> {
            srlRefresh.finishRefresh(2000);//传入false表示刷新失败
            initData();
        });
        //切换中英文
        llTopLeft.setOnClickListener(v -> showLangPop(v));
        //扫一扫
        ivTopRight.setOnClickListener(v -> {
            startActivityForResult(CaptureActivity.class, SCAN_REQUEST_CODE);
        });
        //总钱包
        svAllMoney.setOnSuperTextViewClickListener(superTextView -> {
//            mBundle = new Bundle();
//            mBundle.putString(SpMsg.INTENT_STR, dataBean.getAll_wallet());
//            startActivityForResult(AllMoneyWalletActivity.class, mBundle,REQUEST_CODE);
        });
        //流通钱包
        svCurrentMoney.setOnSuperTextViewClickListener(superTextView -> {
            startActivityForResult(CurrentMoneyActivity.class, REQUEST_CODE);
        });
    }

    private void showLangPop(View v) {

        View view = View.inflate(mContext, R.layout.pop_lang, null);
        LinearLayout llZh = view.findViewById(R.id.ll_zh);
        LinearLayout llEn = view.findViewById(R.id.ll_en);
        llZh.setOnClickListener(v1 -> {
            tvTopLeft.setText(Html.fromHtml("<u>" + getResources().getString(R.string.lang_zh) + "</u>"));
            ivTopLeft.setImageResource(R.mipmap.lang_china);
            mPopupWindow.dismiss();
            need = MultiLanguageUtil.needUpdateLocale(mContext, MultiLanguageType.ZH);
            transLanguage(need, MultiLanguageType.ZH);
        });
        llEn.setOnClickListener(v1 -> {
            tvTopLeft.setText(Html.fromHtml("<u>" + getResources().getString(R.string.lang_en) + "</u>"));
            ivTopLeft.setImageResource(R.mipmap.lang_english);
            mPopupWindow.dismiss();
            need = MultiLanguageUtil.needUpdateLocale(mContext, MultiLanguageType.EN);
            transLanguage(need, MultiLanguageType.EN);
        });
        mPopupWindow = PopWindowUtil.getInstance().makePopupWindow(mContext, view, ViewGroup.LayoutParams.WRAP_CONTENT)
                .showAsDropDown(mContext, v, 0);
    }

    private void transLanguage(boolean need, MultiLanguageType type) {
        if (need) {
            //自己写的常用activity管理工具
            MultiLanguageUtil.updateLanguageEnviroment(mContext, type);
            AppManager.getAppManager().recreateAllOtherActivity(getActivity());
            getActivity().finish();
            startActivity(MainActivity.class);
        }
        mPopupWindow.dismiss();
    }

    @Override
    protected void initData() {
        mPresenter.pGetMain(BaseUrl.INDEX_URL, GetParamUtil.getFragMainParam());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (!isFirsetIncome) {
                initData();
            }
        }
    }

    private void initAdapter() {
        mAdapter = new FMMainMenuAdapter(R.layout.item_fragment_main_menu, menuDatas);
        rvMenu.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (menuDatas.get(position).getType() == NativeGuideBean.TYPE_1) {
                startActivityForResult(menuDatas.get(position).getmClass(), REQUEST_CODE);
            } else if (menuDatas.get(position).getType() == NativeGuideBean.TYPE_2) {
                mBundle = new Bundle();
                mBundle.putString(SpMsg.URL, menuDatas.get(position).getUrl());
                startActivity(WebActivity.class, mBundle);
            }else if (menuDatas.get(position).getType() == NativeGuideBean.TYPE_5) {
                //扫描功能
                startActivityForResult(CaptureActivity.class, SCAN_REQUEST_CODE);
            } else if (menuDatas.get(position).getType() == NativeGuideBean.TYPE_3) {
                toastNotifyShort(R.string.toast_development);
            }
        });
    }

    private void initBiAdapter() {
        biAdapter = new FMMainBiAdapter(R.layout.item_frag_main_bi, coins);
        rvBi.setAdapter(biAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case SCAN_REQUEST_CODE:
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String scanQrCodeStr = data.getStringExtra(CodeUtils.RESULT_STRING);//扫码回调结果
                        if (scanQrCodeStr.contains("?user_id=")){
                            String to_user_id = StringUtil.getSpitRight(scanQrCodeStr, "?user_id=");
                            mBundle = new Bundle();
                            mBundle.putString(SpMsg.INTENT_STR, to_user_id);
                            startActivity(ScanActivity.class, mBundle);
                        }else {
                            //打开外部浏览器
                            if (scanQrCodeStr.startsWith("http")){
                                Intent intent= new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scanQrCodeStr);
                                intent.setData(content_url);
                                startActivity(intent);
                            }else {
                                toastNotifyShort(R.string.scan_qrcode_fail);
                            }
                        }

                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        toastNotifyShort(R.string.scan_qrcode_fail);
                    }
                }
                break;
            case REQUEST_CODE:
                initData();
                break;
        }
    }

    @Override
    public void vGetMainSuccess(FragMainBean dataBean) {
        if (((Activity) mContext).isDestroyed()){
            return;
        }
        this.dataBean = dataBean;
        isFirsetIncome = false;
        coins = dataBean.getCoins();
        tvNickname.setText(dataBean.getUsername());
        String userLevel = "";
        if (!TextUtils.isEmpty(dataBean.getUser_level())){
            userLevel = String.format(getResources().getString(R.string.main_userlevel),dataBean.getUser_level());
        }
        tvUserLevel.setText(userLevel);
        svAllMoney.setCenterTopString(dataBean.getAll_wallet());
        svCurrentMoney.setCenterTopString(dataBean.getCare_wa());
        svNotice.setLeftString(dataBean.getContent());
        if (coins != null && coins.size() != 0) {
            if (biAdapter == null) {
                initBiAdapter();
            } else {
                biAdapter.replaceData(coins);
            }
        }

    }

}
